<template>
  <div class="editing_overview">
    <div class="props_con">
    <!-- {{ expectedObj }} -->
      <div class="props_item" v-show="!item.isClose" v-for="(item, index) in propsList" :key="index">
        <div class="left_icon">
          <img :src="item.img" alt />
        </div>
        <div class="right_con">
          <div class="props_name">{{ item.name }}</div>
          <div class="props_desc">{{ item.desc }}</div>
        </div>
      </div>
    </div>

    <div class="advice_con">
      <div class="top_con">
        <cu-icon class="title_icon" type="icon-jianyi" />
        <div class="title_text">建议</div>
      </div>

      <div class="message_con">
        <template v-for="(item, index) in suggestionList">
          <div
            v-if="!item?.isClose"
            :style="`background: ${item.background};
				border: none;
				padding: 4px 15px;`"
            class="alert"
          >
            <CloseCircleFilled
              style="color: #ff4d4e; margin-right: 8px; vertical-align: middle"
              v-if="item.type === 'error'"
            />
            <ExclamationCircleFilled
              style="color: #faac14; margin-right: 8px; vertical-align: middle"
              v-if="item.type === 'warning'"
            />
            <InfoCircleFilled
              style="color: #7a45fc; margin-right: 8px; vertical-align: middle"
              v-if="item.type === 'info'"
            />
            <span style="color: #fff">{{ item.text }}</span>
            <div class="alert-close">
              <close-outlined
                @click="() => handleClose(index)"
                style="font-size: 12px; color: #fff"
              />
            </div>
          </div>
        </template>

        <div
          class="perfect"
          v-if="suggestionList.every((item) => item.isClose)"
        >
          <LikeOutlined style="font-size: 50px" />
          <span class="mt-20">你的剪辑很完美哦～</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, toRefs, computed, watch } from "vue";
import {
  PlayCircleOutlined,
  HistoryOutlined,
  ExclamationCircleOutlined,
  CloseOutlined,
  LikeOutlined,
  CloseCircleFilled,
  ExclamationCircleFilled,
  InfoCircleFilled,
} from "@ant-design/icons-vue";
import store from "@/store";
import { sumBy, minBy, maxBy } from "lodash";
export default defineComponent({
  components: {
    CloseOutlined,
    ExclamationCircleOutlined,
    LikeOutlined,
    CloseCircleFilled,
    ExclamationCircleFilled,
    InfoCircleFilled,
  },
  setup(props, context) {
    const expectedObj = computed(() => store.getters.expectedVideo);

    // const showText = computed(()=>{
    //   if(expectedObj.value.generation == 0){
    //     return {
    //       videoNum:'0条',
    //       videoDuration:'-'
    //     }
    //   } else {
    //     return {
    //       videoNum:val.generation + "条",
    //       videoDuration:val.duration
    //     }
    //   }
    // })
    const state = reactive({
      suggestionList: [
        {
          type: "error",
          text: "未添加音频或已关闭所有音量，合成的视频将无声",
          background: "rgba(255, 46, 46, 0.15)",
          isClose: false,
        },
        {
          type: "warning",
          text: "当前素材数量过少，建议至少选用10个素材~",
          background: "rgba(254, 195, 20, 0.15)",
          isClose: false,
        },
        {
          type: "warning",
          text: "当前的场景数量过少，建议至少使用3个场景哦~",
          background: "rgba(254, 195, 20, 0.15)",
          isClose: false,
        },
        {
          type: "warning",
          text: "当前口播数量过少，建议至少选用3个口播~",
          background: "rgba(254, 195, 20, 0.15)",
          isClose: true,
        },
        {
          type: "warning",
          text: "当前音乐数量过少，建议至少选用3个音乐或使用随机热门音乐~",
          background: "rgba(254, 195, 20, 0.15)",
          isClose: true,
        },
        {
          type: "info",
          text: "未添加口播，添加口播视频效果更好~",
          background: "rgba(20, 128, 255, 0.15)",
          isClose: false,
        },
        {
          type: "info",
          text: "未添加背景音乐，添加背景音乐视频效果更好~",
          background: "rgba(20, 128, 255, 0.15)",
          isClose: false,
        },
        {
          type: "info",
          text: "建议添加一些文字组合，视频效果会更好~",
          background: "rgba(20, 128, 255, 0.15)",
          isClose: false,
        },
      ],
      propsList: [
        {
          name: "预计可生成",
          desc: expectedObj.value.generation + "条",
          // desc: showText.value.videoNum,
          icon: "PlayCircleOutlined",
          img: "https://hf.pigcms.com/static/wxapp/images/product_img.png",
          // 控制显示, true不显示, false 显示
		  isClose: false
        },
        {
          name: "预计时长(秒)",
          desc: expectedObj.value.duration,
          // desc: showText.value.videoDuration,
          icon: "HistoryOutlined",
          img: "https://hf.pigcms.com/static/wxapp/images/generate_time_img.png",
		  isClose: false
        },
      ],
    });

    const isShowVolumeSuggest = (volume, audio, bgm, bgm_mode) => {
      if (volume?.video_volume > 0) {
        return true;
      }
      if (audio?.length > 0 && volume?.audio_volume > 0) {
        return true;
      }
      if (
        (bgm?.length > 0 || bgm_mode === "random") &&
        volume?.bgm_volume > 0
      ) {
        return true;
      }

      return false;
    };
	
	const edit_model = computed(()=>store.getters.clipJSON?.edit_model)
	
    watch(
      () => store.getters.clipJSON,
      () => {
        const {
          clipJSON: {
            volume,
            resource_data,
            whole_subtitle_config,
            audio,
            bgm,
            bgm_mode,
          },
        } = store.getters;
		
		let totalLength = 0
		// 图文剪辑
    console.log(edit_model.value,'edit_model');
		if(edit_model.value == 5){
			totalLength = sumBy(
			  store.getters.clipJSON?.resource_data,
			  "images.length"
			);
			
			if (totalLength < 10) {
			  state.suggestionList[1].isClose = false;
			} else {
			  state.suggestionList[1].isClose = true;
			}
			
			if(edit_model.value == 5) {
				state.suggestionList[0].isClose = true;
				state.suggestionList[2].isClose = true;
				state.suggestionList[3].isClose = true;
				state.suggestionList[4].isClose = true;
				state.suggestionList[5].isClose = true;
				state.suggestionList[6].isClose = true;
				state.suggestionList[7].isClose = true;
				state.propsList[1].isClose = true;
			} 
		} else {
			totalLength = sumBy(
			  store.getters.clipJSON?.resource_data,
			  "videos.length"
			);
			
			state.suggestionList[0].isClose = isShowVolumeSuggest(
			  volume,
			  audio,
			  bgm,
			  bgm_mode
			);
			
			store.dispatch("SetExpectedVideo", {
			  isVideoMute: !state.suggestionList[0].isClose,
			});
			
			if (totalLength < 10) {
			  state.suggestionList[1].isClose = false;
			} else {
			  state.suggestionList[1].isClose = true;
			}
			
			if (resource_data?.length < 3) {
			  state.suggestionList[2].isClose = false;
			} else {
			  state.suggestionList[2].isClose = true;
			}
			
			if (audio?.length === 0) {
			  state.suggestionList[3].isClose = true;
			  state.suggestionList[5].isClose = false;
			} else {
			  if (audio.length < 3) {
			    state.suggestionList[3].isClose = false;
			  } else {
			    state.suggestionList[3].isClose = true;
			  }
			  state.suggestionList[5].isClose = true;
			}
			
			if (bgm?.length === 0 && bgm_mode === "custom") {
			  state.suggestionList[4].isClose = true;
			  state.suggestionList[6].isClose = false;
			} else {
			  if (bgm.length < 3 && bgm_mode === "custom") {
			    state.suggestionList[4].isClose = false;
			  } else {
			    state.suggestionList[4].isClose = true;
			  }
			  state.suggestionList[6].isClose = true;
			}
			
			if (whole_subtitle_config?.length === 0) {
			  state.suggestionList[7].isClose = false;
			} else {
			  state.suggestionList[7].isClose = true;
			}
		}
      },
      {
        immediate: true,
        deep: true,
      }
    );

    watch(
      () => store.getters.clipJSON,
      (newClipJSON) => {
        const { resource_data, cover_config, edit_model, template_ids } = newClipJSON;
        console.log(newClipJSON,'newClipJSON');
        let generation = 0;
        let duration = "-";
        // 视频时长
		let videoTime = 0;
		if(edit_model == 1 || edit_model == 4) {
			let min = 0;
			let max = 0;
			const num_arr = resource_data
			  ?.filter((i) => i.video?.length > 0)
			  .map((item) => {
			    const _min = minBy(item.video, "material_duration");
			    const _max = maxBy(item.video, "material_duration");
			    min +=
			      item.duration > 0 ? item.duration * 1000 : _min.material_duration;
			    max +=
			      item.duration > 0 ? item.duration * 1000 : _max.material_duration;
			    return item.video.length ? item.video.length : 0;
			  });
			
			videoTime = min;
			
			if (cover_config?.length > 0) {
			  const coverMin = minBy(cover_config, "duration");
			  const coverMax = maxBy(cover_config, "duration");
        console.log(coverMax,'coverMax');
			  min += coverMin.duration * 1000;
			  max += coverMax.duration * 1000;
			}
      console.log(cover_config,'cover_config');
      // console.log(min , max,'min , max');
      
			// if (resource_data?.every((i) => i.video?.length === 0 && (!i.items || i.items.length === 0))) {
			//   duration = "-";
			// } else {
        // if(resource_data?.every((i) => i.items && i.items.length === 0)){
          // duration =
          //   min > 0 && max > 0
          //     ? `${(min / 1000).toFixed(1)} ~ ${(max / 1000).toFixed(1)}`
          //     : "-";
        // }else{

          // debugger
          let accumulatedMax = 0;
          let accumulatedMin = 0;

          resource_data.forEach(element => {
            let currentMax = null;
            let currentMin = null;

            // 如果有items数组，计算items的最大值和最小值
            if (element.items && element.items.length > 0) {
              element.items.forEach(item => {
                const duration = parseFloat(item.duration);
                currentMax = currentMax !== null ? Math.max(currentMax, duration) : duration;
                currentMin = currentMin !== null ? Math.min(currentMin, duration) : duration;
              });
            }else if(element.video && element.video.length > 0){
              element.video.forEach(video => {
                currentMax = (currentMax !== null ? Math.max(currentMax, video.material_duration) : video.material_duration) / 1000;
                currentMin = (currentMin !== null ? Math.min(currentMin, video.material_duration) : video.material_duration) / 1000;
              });

            }
            // 如果没有items数组，则计算video的最大值和最小值

            // 如果找到了当前元素的最大值和最小值，才累积
            if (currentMax !== null) {
              accumulatedMax += currentMax;
            }
            if (currentMin !== null) {
              accumulatedMin += currentMin;
            }
          });
  console.log(accumulatedMax , accumulatedMin,'accumulatedMax , accumulatedMin');
    duration =  accumulatedMin > 0 && accumulatedMax > 0
              ? `${(accumulatedMin).toFixed(1)} ~ ${(accumulatedMax).toFixed(1)}`
              : "-";
              // }
			// }
			generation =
			  num_arr.length > 0 ? num_arr.reduce((pre, curr) => pre * curr, 1) : 0;
		} 
		
		if(edit_model == 3) {
			if(template_ids?.length){
				const min = minBy(template_ids, "material_duration")['material_duration'];
				const max = maxBy(template_ids, "material_duration")['material_duration'];
				duration =
				  min > 0 && max > 0
				    ? `${min.toFixed(1)} ~ ${max.toFixed(1)}`
				    : "-";
            
			} else {
				duration = '-'
			}
			
			function factorial(number) {
			    let factorial = 1;
			    for (let i = 2; i <= number; i++) {
			        factorial *= i;
			    }
			    return factorial;
			}
			function combinations(materials, scenes) {
			    return factorial(materials) / (factorial(scenes) * factorial(materials - scenes));
			}
			
			let sucai_number = resource_data[0]?.video?.length;
			let muban_number = minBy(template_ids, "material_number")?.material_number;
			// console.log("素材数量："+sucai_number + " 模板数量："+muban_number);
			let sucai_and_muban_count = combinations(sucai_number,muban_number);
			let numban_count = factorial(muban_number);
			// console.log("素材根据模板场景组合方式："+sucai_and_muban_count)
			// console.log("模板场景本身组合："+numban_count)
			let zuizhong_count = sucai_and_muban_count * numban_count;
			// console.log("最终生成视频条数："+zuizhong_count)
			if(sucai_number && muban_number && sucai_number>=muban_number){
				generation = zuizhong_count;
			} else {
				generation = 0
			}
		} 
		
		if(edit_model == 5){
			let num_arr = resource_data.filter(item=>item?.images?.length).map(item=>{
				let count = 1
				let result = 0
				if(item.image_tpl == 'single_image'){
					count = 1
					result = item?.images?.length
				} else if(item.image_tpl == 'couple_image_1_1' || item.image_tpl == 'couple_image_9_16' || item.image_tpl == 'couple_image_16_9'){
					count = 2
					result = parseInt(item?.images?.length*(item?.images?.length - 1) / 2)
				} else {
					count = 4
					if(item?.images?.length>4){
						result = parseInt(item?.images?.length*(item?.images?.length - 1)*(item?.images?.length - 2)*(item?.images?.length - 3) / (4*3*2*1))
					} else {
						result = 1
					}
				}
				return result?result:1
			})
			generation =
			  num_arr.length > 0 ? num_arr.reduce((pre, curr) => pre * curr, 1) : 0;
		}

    console.log(generation,
          duration,
          videoTime,'视频时长');
        store.dispatch("SetExpectedVideo", {
          generation,
          duration,
          videoTime,
        });
      },
      {
        deep: true,
        immediate: true,
      }
    );

    watch(
      () => expectedObj.value,
      (val) => {
        console.log(state.propsList,'侦听仓库变化');
        state.propsList[0].desc = val.generation + "条";
        state.propsList[1].desc = val.duration;
        console.log(state.propsList,'侦听仓库变化后');

      },
      {
        deep: true,
      }
    );


    const handleClose = (index) => {
      state.suggestionList[index].isClose = true;
    };

    return {
      ...toRefs(state),
      expectedObj,
      handleClose,
    };
  },
});
</script>

<style lang="less" scoped>
.editing_overview {
  .perfect {
    height: 200px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #8d8d91;
    font-size: 14px;
  }

  .message_con {
    padding-top: 10px;
    .alert {
      position: relative;
      margin-bottom: 5px;

      .alert-close {
        cursor: pointer;
        position: absolute;
        top: 5px;
        right: 15px;
      }
    }
  }
  .props_con {
    margin: 20px 0;
    display: flex;
    transform: translateX(-20px);
    padding: 10px 0;
    .props_item {
      display: flex;
      align-items: center;
      margin-left: 20px;
      cursor: pointer;
      .left_icon {
        img {
          width: 55px;
          height: 55px;
        }
      }
      .right_con {
        display: flex;
        flex-direction: column;
        justify-content: center;
        margin-left: 15px;
        .props_name {
          color: rgb(207, 207, 207);
          font-size: 15px;
        }
        .props_desc {
          color: rgb(255, 255, 255);
          font-size: 18px;
        }
      }
    }
  }

  .advice_con {
    background-color: rgb(43, 43, 46);
    padding: 10px;
    border-radius: 10px;
	min-height: 240px;
    .top_con {
      display: flex;
      align-items: center;
      .title_icon {
        color: #b9bbc1;
        font-size: 18px;
      }
      .title_text {
        color: #b9bbc1;
        margin-left: 5px;
      }
    }
  }
}
</style>
